/**
 * Copyright (c) 2019, Freqchip
 *
 * All rights reserved.
 *
 *
 */

/*
 * INCLUDES
 */
#include "jump_table.h"
#include "co_printf.h"
#include "ble_stack.h"
#include "driver_uart.h"

#include "rtthread.h"
#include "plf.h"


/*
 * MACROS
 */

/*
 * CONSTANTS
 */

/*
 * TYPEDEFS
 */

/*
 * GLOBAL VARIABLES
 */

/*
 * LOCAL VARIABLES
 */
static struct rt_semaphore sem;
/*
 * EXTERN FUNCTIONS
 */
void rtos_baseband_restore_done(void);

/*
 * PUBLIC FUNCTIONS
 */


/*********************************************************************
 * @fn      app_rtos_entry
 *
 * @brief   RTOS relative entries. User should check FreeRTOSConfig.h for function
 *          implementations.
 *          RTOS_ENTRY_TYPE_INIT - used to initialize RTOS. Two tasks has to
 *              be created here, one is for ble stack, one is for dealing GATT messages
 *              (gatt_msg_handler registed by gatt_add_service will be called inside
 *              this task). The ble stack task has to take the most high priority.
 *          RTOS_ENTRY_TYPE_STACK_PUSH - used by lower layer to inform ble stack task
 *              that a new messge has been generated.
 *          RTOS_ENTRY_TYPE_STACK_YIELD - used by ble stack to pend for new message.
 *          RTOS_ENTRY_TYPE_WAKEUP_RESTORE - used to restore RTOS information after wake
 *              up, especially the OS tick information.
 *          RTOS_ENTRY_TYPE_POST_GATT_MSG - used by HOST layer to send GATT message
 *              to gatt_msg_task.
 *
 * @param   type    - @ref RTOS_ENTRY_TYPE_xx
 *          arg     - depend on entry type
 *
 * @return  None.
 */

__attribute__((section("ram_code")))void app_rtos_entry(uint8_t type, void *arg)
{
    if(type == RTOS_ENTRY_TYPE_INIT)
    {

        rt_sem_init(&sem, "sem", 0, RT_IPC_FLAG_FIFO);

        rt_thread_t ble_stack_task_id;
        ble_stack_task_id = rt_thread_create("BLE STACK", (void (*)(void *))ble_stack_schedule, RT_NULL,2048, 2, 20);
        co_printf("task_id:%x\r\n",ble_stack_task_id);
        rt_thread_startup(ble_stack_task_id);

    }
    else if(type == RTOS_ENTRY_TYPE_STACK_PUSH)
    {
				rt_sem_release(&sem);
    }
    else if(type == RTOS_ENTRY_TYPE_STACK_YIELD)
    {
        rt_sem_take(&sem, RT_WAITING_FOREVER);
    }
    else if(type == RTOS_ENTRY_TYPE_WAKEUP_RESTORE)
    {
        rtos_baseband_restore_done();
    }
    else if(type == RTOS_ENTRY_TYPE_POST_GATT_MSG)
    {
        co_printf("RTOS_ENTRY_TYPE_POST_GATT_MSG\r\n");
        //while(xQueueSend(rtos_gatt_msg_queue, arg, 0) != pdTRUE);
    }
}

